﻿using AuthCenter.API.Application.Command.Menu;
using AuthCenter.Domain.Menu;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using MediatR;
using System.Transactions;

namespace AuthCenter.API.Application.Handler.Menu
{
    public class DelMenuHandler : IRequestHandler<DelMenuCommand, APIResult<int>>
    {
        private readonly IBaseRepository<MenuModel> menuRepo;

        public DelMenuHandler(IBaseRepository<MenuModel> menuRepo)
        {
            this.menuRepo = menuRepo;
        }
        public Task<APIResult<int>> Handle(DelMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var res = menuRepo.GetAll().Where(x=>x.Id == request.Id||x.ParentId==request.Id).ToList();
            if (res.Count != 1)
            {
                int r1 = 0;
                foreach (var item in res)
                {
                    item.IsDel = true;
                    r1 = menuRepo.UpdateAsync(item).Result;
                }
                
                result.Message = "删除成功";
                result.Data = r1;
                result.Code = APIEnum.Success;
            }
            else
            {
                var acc = menuRepo.GetAll().FirstOrDefault(x => x.Id == request.Id);
                acc.IsDel = true;
                int r3 = menuRepo.UpdateAsync(acc).Result;
                result.Message = "删除成功";
                result.Data = r3;
                result.Code = APIEnum.Ok;
            }
            return Task.FromResult(result);
        }
    }
}
